import { ValidationArguments, ValidatorConstraint, ValidatorConstraintInterface, ValidatorOptions, registerDecorator } from "class-validator";

@ValidatorConstraint({ name: 'isMatch' })
export class MatchConstraint implements ValidatorConstraintInterface {

    validate(value: any, validationArguments?: ValidationArguments): boolean {
        let [relatedProperty] = validationArguments.constraints
        let relatedValue = ValidatorConstraint[relatedProperty]
        return value == relatedValue
    }

    defaultMessage?(validationArguments?: ValidationArguments): string {
        let [relatedProperty] = validationArguments.constraints
        return `${relatedProperty} and ${validationArguments.property} isn't march`
    }
}
/**
 * 
 * @param AttributeName  表示被比较的值
 * @param validatorOptions Validator-class 的验证规则
 * 
 * 
 * ，而 propertyName 表
 */
export function isMarch(AttributeName: string, validatorOptions: ValidatorOptions) {

    /**
     *@param  obj ：被装饰的实例对象
     *@param  propertyName:示当前被装饰的属性的名称，
     */

    /* 
    target：要验证的对象
options：验证器选项（例如验证器函数）
propertyName：要验证的属性名称
value：要验证的值
constraints：一个包含约束信息的数组，通常用于自定义验证器的参数传递。
    
    */
    return (obj: Record<string, any>, propertyName: string) => {
        return registerDecorator({
            target: obj.constructor,
            options: validatorOptions,
            propertyName,
            validator: MatchConstraint,
            constraints: [AttributeName]

        })
    }
}